package edu.ynu.se.xiecheng.achitectureclass.entity;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter;
import lombok.Setter;

import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;

@Entity
@Getter
@Setter
@DiscriminatorValue("3")
public class Customer extends User{
    @OneToMany(mappedBy = "customer",
            fetch = FetchType.LAZY,
            cascade = CascadeType.ALL)
    @JsonIgnoreProperties("customer")
    private Set<Oorder> oorders;


    public Oorder addOorder(Shop shop){
        AtomicReference<Oorder> oorder = new AtomicReference<>(new Oorder());
        oorder.get().setCustomer(this);
        oorder.get().setPayStatus(0);
        this.oorders.forEach(oldOorder -> {
            oldOorder.getLineItems().forEach(lineItem -> {
                if(lineItem.getShop().equals(shop) && oldOorder.getPayStatus()==0){
                    oorder.set(oldOorder);
                }
            });
        });
        return oorder.get();
    }

    public LineItem selectShopItem(Shop shop, Oorder oorder, Item item,Integer quantity){

        LineItem lineItem = new LineItem();
        lineItem.setShop(shop);
        lineItem.setOorder(oorder);
        lineItem.setItem(item);
        lineItem.setQuantity(quantity);
        Set<LineItem> lineItems = new HashSet<>();
        if ( oorder.getLineItems()!=null){
            lineItems = oorder.getLineItems();
        }
        lineItems.add(lineItem);
        return lineItem;
    }

    public Oorder pay(Oorder oorder){
        oorder.setPayStatus(1);
        return oorder;
    }

    public Customer register(String username, String password){
        this.setUsername(username);
        this.setPassword(password);
        return this;
    }
}
